import React, { useEffect, useRef, useState } from 'react'
import { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Table, message, Typography, Radio } from 'antd'
import moment from 'moment'
import SearchForm from '@components/SearchForm/Index'
import CaseNoRender from '@components/CaseNoRender'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { awaitWrap } from '@js/tool'
import { getData } from './ajax'
import { caseStatusList } from '@js/config'

const { Summary } = Table
const { Row, Cell } = Summary
const { Text } = Typography

// 获取表格字段配置
function getColumns (addWindow) {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60,
      fixed: true
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 140,
      fixed: true,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '办案秘书',
      dataIndex: 'processer',
      key: 'processer',
      width: 100
    },
    {
      title: '仲裁程序',
      dataIndex: 'procedure',
      key: 'procedure',
      width: 150
    },
    {
      title: '收案时间',
      dataIndex: 'accept_datetime',
      key: 'accept_datetime',
      width: 120,
      sorter: true,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '立案时间',
      dataIndex: 'docket_datetime',
      key: 'docket_datetime',
      width: 120,
      sorter: true,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '结案时间',
      dataIndex: 'closure_datetime',
      key: 'closure_datetime',
      width: 120,
      sorter: true,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '结案方式',
      dataIndex: 'closure_type',
      key: 'closure_type',
      width: 120
    },
    {
      title: '收案至立案',
      dataIndex: 'docket2accept',
      key: 'docket2accept',
      sorter: true,
      width: 150
    },
    {
      title: '立案至移交送达',
      dataIndex: 'to_deliver2docket',
      key: 'to_deliver2docket',
      sorter: true,
      width: 200
    },
    {
      title: '移交送达至送达完成',
      dataIndex: 'arrive_datetime2to_deliver',
      key: 'arrive_datetime2to_deliver',
      sorter: true,
      width: 200
    },
    {
      title: '送达完成至移交办案',
      dataIndex: 'to_process2arrive_datetime',
      key: 'to_process2arrive_datetime',
      sorter: true,
      width: 200
    },
    {
      title: '移交办案至第一次组庭',
      dataIndex: 'arbitrator_assign02to_process',
      key: 'arbitrator_assign02to_process',
      sorter: true,
      width: 200
    },
    {
      title: '第一次组庭至第一次开庭',
      dataIndex: 'hearing02arbitrator_assign0',
      key: 'hearing02arbitrator_assign0',
      sorter: true,
      width: 200
    },
    {
      title: '立案至组庭',
      dataIndex: 'arbitrator_assign02docket',
      key: 'arbitrator_assign02docket',
      sorter: true,
      width: 200
    },
    {
      title: '最后开庭至结案',
      dataIndex: 'closure2hearing_datetime',
      key: 'closure2hearing_datetime',
      sorter: true,
      width: 200
    },
    {
      title: '审限',
      dataIndex: 'closure2arbitrator_assign',
      key: 'closure2arbitrator_assign',
      sorter: true,
      width: 100
    },
    {
      title: '立案至结案',
      dataIndex: 'closure2docket',
      key: 'closure2docket',
      sorter: true,
      width: 150
    },
    {
      title: '结案至归档',
      dataIndex: 'file2closure_datetime',
      key: 'file2closure_datetime',
      sorter: true,
      width: 150
    },
    {
      title: '扣除审限天数',
      dataIndex: 'days_sum_unlimit',
      key: 'days_sum_unlimit',
      sorter: true,
      width: 150
    },
    {
      title: '开庭次数',
      dataIndex: 'hearing_count',
      key: 'hearing_count',
      width: 150
    },
    {
      title: '组庭次数',
      dataIndex: 'arbitrator_assign_count',
      key: 'arbitrator_assign_count',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 100,
      fixed: 'right',
      render: (value, line) => {
        return (<span className={style['operate-btn']} onClick={() => openDetail(addWindow, line)}>详情</span>)
      }
    }
  ]
}

// 前往详情
function openDetail (addWindow, data) {
  addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id, operate: 'yanchangshenxian' } })
}

const extendParams = [

]

const currentYear = moment().year()
const end = moment(`${currentYear + 1}-01-01 00:00:00`)
end.subtract(1, 'second')

const initialValues = {
  count_inlimit: 0,
  beginTime: moment(`${currentYear}-01-01 00:00:00`),
  endTime: end
}

// 改变分页
function tableChange ({ current, pageSize }, sorter, setCurrent, setPageSize, setOrderField, setOrder) {
  setCurrent(current)
  setPageSize(pageSize)
  setOrderField(sorter.field)
  setOrder(sorter.order)
}

// 获取案件状态
function getStatus (status) {
  if (status === '全部') {
    return { k: 'status', o: 'not in', v: '未提交,待审核,已提交' }
  }
  return { k: 'status', o: '=', v: status }
}

// 获取数据
async function getTableData (condition, current, pageSize, orderField, order, status, setTotal, setList, setAvg, setLoading) {
  const c = [...condition]
  const s = getStatus(status)
  c.push(s)
  setLoading(true)
  const [e, d] = await awaitWrap(getData(current, pageSize, orderField, order, c))
  setLoading(false)
  if (e) {
    return message.warning(e.message)
  }
  const list = d.list.map((li, i) => {
    li.key = pageSize * (current - 1) + i + 1
    return li
  })
  setList(list)
  setTotal(d.total)
  setAvg(d.avgs !== null ? d.avgs : {})
}

// 处理搜索表单扩展字段
function extendCondition (condition, formData) {
  return { condition, formData }
}

function renderSummary (arg) {
  return (
    <Summary fixed>
      <Row>
        <Cell index={0} colSpan={2}><Text>平均值</Text></Cell>
        <Cell index={2}><Text /></Cell>
        <Cell index={3}><Text /></Cell>
        <Cell index={4}><Text /></Cell>
        <Cell index={5}><Text /></Cell>
        <Cell index={6}><Text /></Cell>
        <Cell index={7}><Text /></Cell>
        <Cell index={8}><Text>{arg.docket2accept_avg}</Text></Cell>
        <Cell index={9}><Text>{arg.to_deliver2docket_avg}</Text></Cell>
        <Cell index={10}><Text>{arg.arrive_datetime2to_deliver_avg}</Text></Cell>
        <Cell index={11}><Text>{arg.to_process2arrive_datetime_avg}</Text></Cell>
        <Cell index={12}><Text>{arg.arbitrator_assign02to_process_avg}</Text></Cell>
        <Cell index={13}><Text>{arg.hearing02arbitrator_assign0_avg}</Text></Cell>
        <Cell index={14}><Text>{arg.arbitrator_assign02docket_avg}</Text></Cell>
        <Cell index={15}><Text>{arg.closure2hearing_datetime_avg}</Text></Cell>
        <Cell index={16}><Text>{arg.closure2arbitrator_assign_avg}</Text></Cell>
        <Cell index={17}><Text>{arg.closure2docket_avg}</Text></Cell>
        <Cell index={18}><Text>{arg.file2closure_datetime_avg}</Text></Cell>
        <Cell index={19}><Text /></Cell>
        <Cell index={20}><Text /></Cell>
        <Cell index={21}><Text /></Cell>
        <Cell index={22}><Text /></Cell>
      </Row>
    </Summary>
  )
}

function Main ({ title, meta, addWindow }) {
  const [ready, setReady] = useState(false)
  const [condition, setCondition] = useState([])
  const [status, setStatus] = useState('全部')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [orderField, setOrderField] = useState()
  const [order, setOrder] = useState()
  const [avg, setAvg] = useState({})
  const [pagination, setPagination] = useState({
    current,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  const formRef = useRef(null)
  useEffect(() => {
    const c = formRef.current
    c.showAll()
    c.resetFields()
    c.setFieldsValue(meta ? meta.formData : {})
    setTimeout(() => {
      c.submit()
    }, 0)
  }, [formRef, meta])
  useEffect(() => {
    const p = pagination
    if (p.current !== current || p.pageSize !== pageSize || p.total !== total) {
      setPagination({
        ...p,
        current,
        pageSize,
        total
      })
    }
  }, [current, pageSize, pagination, total])
  useEffect(() => {
    if (ready) {
      getTableData(condition, current, pageSize, orderField, order, status, setTotal, setList, setAvg, setLoading)
    }
  }, [condition, current, pageSize, ready, orderField, order, status])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchForm
        ref={formRef} params={['caseno', 'processerid', 'closure_type', 'type', 'beginTime', 'endTime', 'procedure', 'cause_action']} initialValues={initialValues} extendParams={extendParams} extendCondition={(c, f) => extendCondition(c, f)} onChange={d => {
          setCondition(d); setCurrent(1); setReady(true)
        }}
      />
      <div className={style['table-btns-line']}>
        <div className={style['table-tabs-container']}>
          <Radio.Group value={status} onChange={v => setStatus(v.target.value)}>
            <Radio.Button value='全部'>全部</Radio.Button>
            {caseStatusList.map(li => <Radio.Button value={li} key={li}>{li}</Radio.Button>)}
          </Radio.Group>
        </div>
      </div>
      <div className={style['table-container']} style={{ width: 'calc(100vw - 225px)' }}>
        <Table scroll={{ x: 2260, y: 600 }} loading={loading} columns={getColumns(addWindow)} dataSource={list} pagination={pagination} summary={() => renderSummary(avg)} onChange={(v, filters, sorter) => tableChange(v, sorter, setCurrent, setPageSize, setOrderField, setOrder)} sticky />
      </div>
    </div>
  )
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(Main)
